package ynu.edu.online_course.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import ynu.edu.online_course.entity.UserRole;
import ynu.edu.online_course.service.UserRoleService;

import java.util.List;

@RestController
@RequestMapping("user-roles")
public class UserRoleController {

    @Autowired
    private UserRoleService userRoleService;

    // 获取用户的角色列表
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserRoles(@PathVariable Long userId) {
        try {
            List<UserRole> roles = userRoleService.getRolesByUserId(userId);
            if (roles == null || roles.isEmpty()) {
                return ResponseEntity.status(404).body("No roles found for user ID: " + userId);
            }
            return ResponseEntity.ok(roles);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body("Internal server error: " + e.getMessage());
        }
    }

    // 为用户分配角色
    @PostMapping
    public ResponseEntity<?> addUserRole(@RequestBody UserRole userRole) {
        userRoleService.addUserRole(userRole);
        return ResponseEntity.ok("User role assigned successfully");
    }

    // 删除用户角色
    @DeleteMapping("/user/{userId}/role/{roleId}")
    public ResponseEntity<?> deleteUserRole(@PathVariable Long userId, @PathVariable Long roleId) {
        userRoleService.deleteUserRole(userId, roleId);
        return ResponseEntity.ok("User role deleted successfully");
    }
}
